package com.ztgf.shopping.api.client.shop;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.qiyuesuo.sdk.v2.SdkClient;
import com.qiyuesuo.sdk.v2.request.ContractDownloadRequest;
import com.qiyuesuo.sdk.v2.utils.IOUtils;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.order.models.dto.OrderContractRelationDTO;
import com.ztgf.order.models.service.IOrderContractRelationService;
import com.ztgf.shopping.models.bo.shop.ShopQiyuesuoAuthCallBackInfoBO;
import com.ztgf.shopping.models.bo.shop.ShopQiyuesuoAuthStateInfoBO;
import com.ztgf.shopping.models.bo.shop.ShopQiyuesuoInfoBO;
import com.ztgf.shopping.models.dto.shop.ShopQiyuesuoInfoDTO;
import com.ztgf.shopping.models.service.shop.IShopQiyuesuoInfoService;
import com.ztgf.sms.models.dto.sms.SmsInfoDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 契约锁店铺信息控制器
 *
 * @author YUE
 * @Date 2020-06-15 16:18:38
 */

@RestController
@RequestMapping("/api/shopQiyuesuoInfo")
@Slf4j
@Api(value = "ShopQiyuesuoInfoApiController", tags = "契约锁店铺信息Api接口")
public class ShopQiyuesuoInfoApiController {

    @Value("${shop.qiyuesuo.service.sdkUrl}")
    private String serverUrl;

    @Value("${shop.qiyuesuo.service.appToken}")
    private String accessKey;

    @Value("${shop.qiyuesuo.service.appSecret}")
    private String accessSecret;

    @DubboReference
    private IShopQiyuesuoInfoService shopQiyuesuoInfoService;

    @DubboReference
    private IOrderContractRelationService orderContractRelationService;


    /**
     * 根据订单id下载合同
     *
     * @param orderId 订单id
     * @return
     */
    @GetMapping("/orderContractDownload/{orderId}")
    public void orderContractDownload(@PathVariable(value = "orderId") Long orderId, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition", "attachment;fileName=" + orderId + ".zip");
        OrderContractRelationDTO orderContractRelationDTO = orderContractRelationService.getByOrderId(orderId);
        SdkClient sdkClient = new SdkClient(serverUrl, accessKey, accessSecret);
        // 下载合同
        //Long.parseLong(orderContractRelationDTO.getContractId())
        ContractDownloadRequest request = new ContractDownloadRequest(Long.parseLong(orderContractRelationDTO.getContractId()));
        List<String> str = new ArrayList<>();
        str.add("CONTRACT");
        request.setDownloadItems(str);
        log.info(request.getUrl());
        OutputStream fos = response.getOutputStream();
        //FileOutputStream fos = new FileOutputStream("E:/module/doc.zip");
        sdkClient.download(request, fos);
        IOUtils.safeClose(fos);
        log.info("下载合同成功");
    }

    /**
     * 企业验证回调地址
     *
     * @param shopQiyuesuoAuthCallBackInfoBO
     * @return
     */
    @PostMapping("/getCallBackAuthInfo")
    public Map getCallBackAuthInfo(ShopQiyuesuoAuthCallBackInfoBO shopQiyuesuoAuthCallBackInfoBO) {
        log.info("企业验证回调了");
        shopQiyuesuoInfoService.updateByCallBackInfo(shopQiyuesuoAuthCallBackInfoBO);
        Map result = new HashMap();
        result.put("code", 1001);
        return result;
    }

    /**
     * 合同状态发生改变回调
     *
     * @param signature
     * @param timestamp
     * @return
     */
    @PostMapping("/getCallBackContactInfo")
    public String getCallBackContactInfo(@RequestParam(required = false) String content, @RequestParam(required = false) String signature, @RequestParam(required = false) String timestamp) throws Exception {
        log.info("合同状态回调了");
        return shopQiyuesuoInfoService.updateContactByCallBackInfo(signature, timestamp, content);
    }
//
//    /**
//     * 德邦合同状态发生改变回调
//     *
//     * @param signature
//     * @param timestamp
//     * @return
//     */
//    @PostMapping("/getCallBackContactDebang")
//    public String getCallBackContactDebang(@RequestParam(required = false) String content, @RequestParam(required = false) String signature, @RequestParam(required = false) String timestamp) throws Exception {
//        log.info("合同状态回调了");
//        return shopQiyuesuoInfoService.updateContactByCallBackInfo(signature, timestamp, content);
//    }


    /**
     * 判断是否有电子签章
     *
     * @param shopId
     * @return
     */
    @ApiOperation(value = "判断是否有电子签章", notes = "判断是否有电子签章")
    @PostMapping("/getCompanyAuth")
    public Result getCompanyAuth(Long shopId) {
        ShopQiyuesuoAuthStateInfoBO shopQiyuesuoAuthStateInfoBO = shopQiyuesuoInfoService.getByQiyuesuoState(shopId);
        return new Result<>(shopQiyuesuoAuthStateInfoBO);
    }


    /**
     * 查看合同
     *
     * @return
     */
    @ApiOperation(value = "查看合同返回合同url", notes = "查看合同返回合同url")
    @PostMapping("/getContactUrl")
    public Result<String> getContactUrl(Long contractId) {
        String contractString = shopQiyuesuoInfoService.getContractString(contractId);
        return new Result<>(contractString);
    }


//    /**
//     *获取签署页面 根据订单id
//     * @param orderId 订单id
//     * @param id 签署人店铺id
//     * @return
//     */
//    @ApiOperation(value = "获取签署页面 根据订单id",notes = "获取签署页面 根据订单id")
//    @PostMapping("/getSignaturePage")
//    public Result<String> getSignaturePage(Long orderId,Long id){
//        String signatureUrl = orderContractRelationService.getSignaturePage(orderId, id);
//        return new Result<>(signatureUrl);
//    }

//    /**
//     *
//     * @param buyShopId 买家id
//     * @param selleShopId 卖家id
//     * @return
//     */
//    @ApiOperation(value = "发起合同并且返回合同url",notes = "发起合同并且返回合同url")
//    @PostMapping("/sendAndGetContactUrl")
//    public Result<String> sendAndGetContactUrl(Long buyShopId,Long selleShopId,Long orderId,@RequestParam(value = "param",required = false) String param) throws Exception {
//        String contactId = shopQiyuesuoInfoService.promoteContract(buyShopId,selleShopId,orderId,param); //創建合同
//        String contractString = shopQiyuesuoInfoService.getContractString(Long.parseLong(contactId));
//        return new Result<>(contractString);
//    }

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找", notes = "根据id查找")
    @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
    public Result<ShopQiyuesuoInfoDTO> get(@RequestParam("id") Long id) {
        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        ShopQiyuesuoInfoDTO dto = shopQiyuesuoInfoService.selectById(id);

        return new Result<>(dto);
    }

    @ApiOperation(value = "契约锁店铺信息列表", notes = "契约锁店铺信息列表")
    @PostMapping("/queryPageList")
    public Result<Page<ShopQiyuesuoInfoDTO>> queryPageList(ShopQiyuesuoInfoBO bo) {
        Wrapper<ShopQiyuesuoInfoDTO> wrapper = new EntityWrapper<>();
        if (bo.getStatus() != null) {
            wrapper.eq("status", bo.getStatus());
        }
        if (bo.getStartDate() != null) {
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null) {
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<ShopQiyuesuoInfoDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = shopQiyuesuoInfoService.selectPage(page, wrapper);

        return new Result<>(page);
    }

//    @ApiOperation(value = "契约锁修改电话号码发送短信", notes = "契约锁修改电话号码发送短信")
//    @PostMapping("/updatePhone")
//    public Result updatePhone(ShopQiyuesuoInfoDTO bo) {
//
//
//        boolean b = shopQiyuesuoInfoService.updatePhoneById(bo);
//        if (b){
//            return new Result(CodeEnum.FAIL_Send_1010);
//        }
//
//        return new Result<>();
//    }

    @ApiOperation(value = "契约锁修改电话号码校验验证码", notes = "契约锁修改电话号码校验验证码")
    @PostMapping("/CheckPhone")
    public Result CheckPhone(Long shopId,String captcha,String newCaptcha,String mobile,String newMobile) {



        boolean b = shopQiyuesuoInfoService.CheckPhone(shopId,captcha,newCaptcha,mobile,newMobile);
        if (!b){
            return new Result(CodeEnum.FAIL_Login_1006);
        }

        return new Result<>();
    }


    @ApiOperation(value = "契约锁根据shopId查询", notes = "契约锁根据shopId查询")
    @PostMapping("/qureyByShopId")
    public Result<ShopQiyuesuoInfoDTO> qureyByShopId(Long shopId) {

        EntityWrapper<ShopQiyuesuoInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id",shopId);
        ShopQiyuesuoInfoDTO shopQiyuesuoInfoDTO = shopQiyuesuoInfoService.selectOne(wrapper);
        if (shopQiyuesuoInfoDTO==null){
            return new Result(CodeEnum.FAIL_100036);
        }

        return new Result<>(shopQiyuesuoInfoDTO);
    }


}
